package cn.gok.client.service.impl;

import cn.gok.client.service.AdressSercice;
import cn.gok.common.dao.customer.CustomerBalanceLogDao;
import cn.gok.common.dao.customer.CustomerConsigneeDao;
import cn.gok.common.dao.customer.CustomerInfoDao;
import cn.gok.common.dao.customer.CustomerLoginDao;
import cn.gok.common.entity.adress.Area;
import cn.gok.common.entity.adress.City;
import cn.gok.common.entity.adress.Province;
import cn.gok.common.entity.customer.CustomerBalanceLog;
import cn.gok.common.entity.customer.CustomerConsignee;
import cn.gok.common.entity.customer.CustomerInfo;
import cn.gok.common.entity.customer.CustomerLogin;
import cn.gok.client.service.CustomerService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.IPage;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : shikundai
 * @Time: 2020/9/27  11:09
 * @description: 顾客信息业务逻辑层接口实现
 */
@Slf4j
@Service
public class CustomerServiseImpl implements CustomerService {
    @Autowired
    private CustomerInfoDao customerInfoDao;
    @Autowired
    private CustomerConsigneeDao customerConsigneeDao;
    @Autowired
    private CustomerLoginDao customerLoginDao;
    @Autowired
    private AdressSercice adressSercice;
    @Autowired
    private CustomerBalanceLogDao customerBalanceLogDao;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addCustomer(CustomerLogin customerLogin, CustomerInfo customerInfo, CustomerConsignee customerConsignee) {
        /*
         * 检测登录名是否存在
         * */
        if (verificationLoginName(customerLogin.getLoginName())) {
            throw new RuntimeException("该用户已经注册!");
        }
        //获得当前时间作为更新时间
        Date date = new Date();

        /*
         * 插入登录信息
         * */
        //完善登录信息
        customerLogin.setModifiedTime(date);
        //登录的用户名加密 (加密999次)
        String secretPsw = new Md5Hash(customerLogin.getPassword(), null, 999).toString();
        customerLogin.setPassword(secretPsw);
        //设置顾客ID为当前时间戳
        String cID = String.valueOf(System.currentTimeMillis());
        customerLogin.setCustomerId(cID);

        int out1 = customerLoginDao.insert(customerLogin);

        if (out1 <= 0) {
            throw new RuntimeException("插入登录信息失败");
        }
        /*
         * 插入顾客信息
         * */
        //设置顾客注时间
        customerInfo.setRegisterTime(date);
        //完善顾客最后更新时间
        customerInfo.setModifiedTime(date);
        //完善消费者ID，以当前时间戳
        customerInfo.setCustomerId(customerLogin.getCustomerId());
        //设置顾客名字为登录名
        customerInfo.setCustomerName(customerLogin.getLoginName());
        //设置顾客的城市
        City city = adressSercice.getCity(customerConsignee.getCity());
        customerInfo.setCity(city.getCity());
        //调用插入方法插入数据
        int out2 = customerInfoDao.insert(customerInfo);
        if (out2 <= 0) {
            throw new RuntimeException("插入顾客信息失败");
        }
        /*
         * 插入地址信息
         * */
        //完善地址信息的更新时间
        customerConsignee.setModifiedTime(date);
        //设置地址的顾客ID
        customerConsignee.setCustomerId(customerLogin.getCustomerId());
        //设置地址用户名
        customerConsignee.setCustomerUsername(customerInfo.getCustomerName());
        //设置省份
        Province province = adressSercice.getProvince(customerConsignee.getProvince());
        customerConsignee.setProvince(province.getProvince());
        //设置城市
        customerConsignee.setCity(city.getCity());
        //设置区域
        Area area = adressSercice.getArea(customerConsignee.getDistrict());
        customerConsignee.setDistrict(area.getArea());

        //插入地址信息
        int out3 = customerConsigneeDao.insert(customerConsignee);
        if (out3 <= 0) {
            throw new RuntimeException("插入地址信息失败");
        }

        return true;
    }

    @Override
    public boolean verificationLoginName(String loginName) {
        /*
         * 构造条件，验证登录名是否存在
         * */
        QueryWrapper<CustomerLogin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("LOGIN_NAME", loginName);
        /*
         * 查询数据
         * */
        List<CustomerLogin> customerLogins = customerLoginDao.selectList(queryWrapper);
        return customerLogins.size() > 0 ? true : false;
    }

    @Override
    public boolean login(HttpServletRequest req, CustomerLogin customerLogin) {
        //密码加密999次
        String psw = new Md5Hash(customerLogin.getPassword(), null, 999).toString();
        customerLogin.setPassword(psw);
        /*
         * 通过登录名和密码查询顾客信息
         * */

        QueryWrapper<CustomerLogin> wrapper = new QueryWrapper<>();
        wrapper.setEntity(customerLogin);

        CustomerLogin out = customerLoginDao.selectOne(wrapper);

        if (out == null) {
            throw new RuntimeException("用户名或密码出错");
        } else {
            req.getSession().setAttribute("customerId", out.getCustomerId());
        }
        return true;
    }

    @Override
    public Map getCustomerMsg(String customerID) {
        /*
         * 通过顾客ID获取顾客登录信息
         * */
        CustomerLogin customerLogin = customerLoginDao.selectById(customerID);
        //数据异常抛出错误
        if (customerLogin == null) {
            throw new RuntimeException("该顾客信息不存在！");
        }
        /*
         *通过顾客ID获取顾客详细信息
         * */
        QueryWrapper<CustomerInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("CUSTOMER_ID", customerID);
        CustomerInfo customerInfo = customerInfoDao.selectOne(wrapper);
        //数据异常抛出错误
        if (customerInfo == null) {
            throw new RuntimeException("该顾客信息不存在！");
        }
        /*
         * 通过顾客Id获取顾客地址
         * */
        QueryWrapper<CustomerConsignee> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("CUSTOMER_ID", customerID);
        List<CustomerConsignee> consignees = customerConsigneeDao.selectList(wrapper1);
        //数据异常抛出错误
        if (customerLogin == null) {
            throw new RuntimeException("该顾客信息异常！");
        }
        /*
         * 数据整合返回
         * */
        Map map = new HashMap();
        //放入顾客登录信息
        map.put("customerLogin", customerLogin);
        //放入顾客详细信息
        map.put("customerInfo", customerInfo);
        //放入顾客地址信息（集合）
        map.put("consignees", consignees);

        return map;
    }

    @Override
    public boolean updateCustomer(CustomerInfo customerInfo) {
        /*
         * 设置注册时间为空，不更改
         * */
        customerInfo.setRegisterTime(null);
        /*
         * 设置最后更新时间
         * */
        customerInfo.setModifiedTime(new Date());

        int out = customerInfoDao.updateById(customerInfo);
        return out > 0 ? true : false;
    }

    @Override
    public boolean updatePsw(String customerId, String oldPsw, String psw) {
        /*
         * 旧密码验证
         * */
        //加密
        oldPsw = new Md5Hash(oldPsw, null, 999).toString();
        //设置信息
        CustomerLogin customerLogin = new CustomerLogin();
        customerLogin.setCustomerId(customerId);
        customerLogin.setPassword(oldPsw);
        //查询验证密码是否正确
        QueryWrapper<CustomerLogin> wrapper = new QueryWrapper<>();
        wrapper.setEntity(customerLogin);

        CustomerLogin out = customerLoginDao.selectOne(wrapper);
        if (out == null) {
            //密码错误
            throw new RuntimeException("密码出错！");
        }

        /*
         * 把新密码插入进去
         * */
        psw = new Md5Hash(psw, null, 999).toString();
        out.setPassword(psw);
        out.setModifiedTime(new Date());
        //更新并返回结果
        return customerLoginDao.updateById(out) > 0 ? true : false;
    }

    @Override
    public PageInfo<CustomerBalanceLog> getCustomerBalanceLog(String time, int page, int pageSize) {
        /*
         * 正则校验是否符合规则
         * */
        String regex = "^[0-9]{4}-[0-9]{2}-[0-9]{2}";
        if (!time.matches(regex)) {
            throw new RuntimeException("数据不匹配");
        }
        PageHelper.startPage(page, pageSize);
        //执行查询操作
        List<CustomerBalanceLog> list = customerBalanceLogDao.gtCustomerBalanceLogs(time);
        PageInfo<CustomerBalanceLog> pageInfo=new PageInfo<>(list);
        return pageInfo;
    }
}
